<template>
	<view class="code-container">
		<view class="vCode-btn" :class="runTime ? 'disabled' : ''" @click="getForm">
			{{runTime ? `${time}秒后重新获取` : "获取验证码"}}
		</view>
	</view>
</template>

<script>
	export default {
		name:"SendCode",
		
		data() {
			return {
				timeId:null,
				time:60,
				runTime:false,
			
			};
		},
		methods: {
			getForm() {
				if(this.timeId !== null){
					return
				}
			//生成事件，获取表单信息
				this.$emit("getForm",this.handlePhone)
			},
			
		 async   handlePhone(from){
			 //获取手机号码
				const {phone} = await from.validateField(['phone'])
				
			 //倒计时显示 
			 this.runTime = true
			 this.timeRunning()
			 
			 //发送请求
			 const {mobileCode,msg} = await this.$http.get_code(phone)
			 uni.showToast({
			 	title:msg,
				icon:"none"
			 });
			this.$emit("setCode",mobileCode)
			},
			
			//倒计时显示
			timeRunning(){
			
				this.timeId = setInterval(()=>{
					this.time--
					if(this.time === 0){
						clearInterval(this.timeId)
						this.timeId = null
						this.runTime = false
						this.time = 60
						return
					}
					
				},1000)
			},
		},
		beforeDestroy() {
			clearInterval(this.timeId)
			this.timeId = null
			this.runTime = false
			this.time = 60
			return
		}
	}
</script>

<style lang="scss" scoped>
.code-container{
	flex-shrink: 0;
	margin:0  20rpx;
	.vCode-btn{
		background-color: $base-color;
		color: #fff;
		padding: 20rpx;
		border-radius: 10rpx;
		opacity: .8;
	  &.disabled{
		  background-color: #ff9d8e;
	  }
	}
}
</style>